package com.adingxiong.springsecurityoauth2.oauth.config;

import com.adingxiong.springsecurityoauth2.oauth.handler.MyAuthenticationFailureHandler;
import com.adingxiong.springsecurityoauth2.oauth.handler.MyAuthenticationSucessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName MySecurityConfig
 * @Description @Order(2)  配置服务加载的优先级   数字越小 优先级越高 避免资源服务收到拦截无法访问
 *
 *      支持认证模式和密码模式
 *
 * @Author xiongchao
 * @Date 2020/10/29 13:33
 **/
@Order(2)
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }


    /**
     * 密码模式需要用到该认证方式
     * @return  不能写@Override 不然会报错 占内存溢出
     * @throws Exception
     */

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/login")
                .successHandler(authenticationSucessHandler())
                .failureHandler(authenticationFailureHandler())
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .antMatchers("/oauth/**","/login/**","/logout/**").permitAll()
                .and()
                .csrf().disable();


        http.requestMatchers()
                .antMatchers("/oauth/**","/login/**","/logout/**")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .and()
                .csrf().disable()
                .formLogin().permitAll();
    }

    @Bean
    public MyAuthenticationSucessHandler authenticationSucessHandler(){
        return  new MyAuthenticationSucessHandler();
    }

    public MyAuthenticationFailureHandler authenticationFailureHandler(){
        return new MyAuthenticationFailureHandler();
    }
}
